<template>
  <label class="v-switch-group">
    <input
      type="checkbox"
      :name="name"
      v-model="_value"
      @change="handleChange"
    />
    <span class="v-switch-core"></span>
    <span class="v-switch-toggle"></span>
  </label>
</template>
<script>
export default {
  name: 'switch',
  props: {
    name: String,
    value: Boolean,
  },
  data() {
    return {
      currentValue: this.value,
    }
  },
  computed: {
    _value: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('input', val)
      },
    },
  },
  watch: {
    value(val) {
      this.setCurrentValue(val)
    },
  },
  methods: {
    handleChange(event) {
      this.setCurrentValue(event.target.value)
    },
    setCurrentValue(value) {
      if (value === this.currentValue) return
      this.currentValue = value
      this.$emit('change', value)
    },
  },
}
</script>
<style lang="scss">
@import "~styles/variables";
$width: 34px;
$height: 14px;
$animateDuration: .3s;

.v-switch-group {
  display: inline-block;
  margin: (($height * 1.5 - $height) / 2);
  width: $width;
  height: $height;
  text-align: center;
  position: relative;
  label {
    -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
  }
}

label > * { pointer-events: none; }

input[type='checkbox'] {
  display: none;
  &:checked ~ .v-switch-toggle {
    background: $primaryColor;
    left: ($width - ($height * 1.4 - $height) / 2) - $height;
    transition: $animateDuration;
  }
  &:checked ~ .v-switch-core {
    background: $primaryColor;
    opacity: .5;
    transition: $animateDuration;
  }
}

.v-switch-core {
  display: block;
  width: $width;
  height: $height;
  background: rgba(34, 31, 31, 0.26);
  border-radius: $height / 2;
  position: absolute;
  top: 0;
  transition: $animateDuration;
}

.v-switch-toggle {
  height: $height * 1.4;
  width: $height * 1.4;
  border-radius: 50%;
  background: #f1f1f1;
  position: absolute;
  top: ($height * 1.4 - $height) / -2;
  left: ($height * 1.4 - $height) / -2;
  box-shadow: 0 $width / 50 $width / 25 rgba(black, .4);
  transition: $animateDuration;
}
</style>
